package com.hanshg.cherry.security;

import com.hanshg.cherry.config.sms.SmsCodeAuthenticationSecurityConfig;
import com.hanshg.cherry.security.authentication.MyAuthenctiationFailureHandler;
import com.hanshg.cherry.security.authentication.MyAuthenticationSuccessHandler;
import com.hanshg.cherry.security.authentication.MyLogoutSuccessHandler;
import com.hanshg.cherry.security.authentication.RestAuthenticationAccessDeniedHandler;
import com.hanshg.cherry.security.filter.VerifyCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

/**
 * @author 柠檬水
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    // 过滤不需要认证的连接
    private static final String[] MATCHERS_PERMITALL_URL = {
            "/login.html", "/smslogin.html", "/user-register.html", "/doc.html", "/register/**",
            "/sms/**", "/authLogin/**", "/callback*",
            "/kaptcha/**", "/xadmin/**", "/upload/**", "/my/**",
            "/ztree/**", "/treetable-lay/**", "/static/**", "/client/**", "/file/**"
    };

    @Autowired
    @Qualifier("normalUserDetailService")
    private UserDetailsService userDetailsService;

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private MyAuthenctiationFailureHandler myAuthenctiationFailureHandler;

    @Autowired
    private RestAuthenticationAccessDeniedHandler restAuthenticationAccessDeniedHandler;

    @Autowired
    private MyLogoutSuccessHandler myLogoutSuccessHandler;

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private VerifyCodeFilter verifyCodeFilter;

    @Autowired
    private PersistentTokenRepository tokenRepository;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //记住我处理 2天有效期
        http.rememberMe().tokenRepository(tokenRepository)
                .tokenValiditySeconds(7 * 24 * 60 * 60)//有效时长(秒)
                .userDetailsService(userDetailsService);

        //关闭CSRF
        http.csrf().disable();

        //加入验证码过滤器
        http.addFilterBefore(verifyCodeFilter, AbstractPreAuthenticatedProcessingFilter.class);

        //认证
        http.apply(smsCodeAuthenticationSecurityConfig).and().authorizeRequests()
                //排除不进行安全认证的文件
                .antMatchers(MATCHERS_PERMITALL_URL)
                .permitAll()
                .anyRequest()
                .authenticated();
        //设置用户seesion超时调整地址
        http.sessionManagement().invalidSessionUrl("/login.html")
                //默认
                .sessionFixation().migrateSession();
        //设置登录人数
        //.maximumSessions(1)
        //.maxSessionsPreventsLogin(false)
        //超时的提示处理
        //.expiredSessionStrategy(myExpiredSessionStrategy);

        //解决X-Frame-Options 跨域问题
        http.headers().frameOptions().disable();   //sameOrigin();
        //提交表单验证处理
        http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .successHandler(myAuthenticationSuccessHandler)
                .failureHandler(myAuthenctiationFailureHandler)
                .and().logout()
                .permitAll()
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .logoutSuccessHandler(myLogoutSuccessHandler);

        //异常处理
        http.exceptionHandling().accessDeniedHandler(restAuthenticationAccessDeniedHandler);
    }

}
